package dialog

import (
	"context"

	"paper-pro/app/chat/api/internal/svc"
	"paper-pro/app/chat/api/internal/types"
	"paper-pro/pkg/ctxdata"
	"paper-pro/pkg/rpc/chat/client/chatdialogservice"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// list assistant:id chat dialogs
func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListLogic) List(req *types.DialogListReq) (resp *types.DialogListResp, err error) {
	userId, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(err, "Chat Dialogs List: get UserId error: %v", err)
	}

	rpcResp, err := l.svcCtx.ChatDialogRpc.List(l.ctx, &chatdialogservice.ChatDialogListReq{
		AssistantId: req.AssistantId,
		UserId:      userId,
	})
	if err != nil {
		return nil, errors.Wrapf(err, "Chat Dialogs List: ChatDialogRpc List error: %v", err)
	}

	dialogs := make([]types.ChatDialog, len(rpcResp.Dialogs))
	for i, dia := range rpcResp.Dialogs {
		_ = copier.Copy(&dialogs[i], &dia)
	}
	resp = &types.DialogListResp{
		Dialogs: dialogs,
	}

	return
}
